<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">个人信息</h2>
      <el-tag v-if="adminInfo.level" type="info">{{ adminInfo.label }}</el-tag>
    </div>

    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="startEdit">编辑</el-button>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="profileData"
            :rules="rules"
            label-width="120px"
            :disabled="!isEditing"
          >
            <el-form-item label="教师工号" prop="usercode">
              <el-input v-model="profileData.usercode" :disabled="true" />
            </el-form-item>
            
            <el-form-item label="姓名" prop="fullName">
              <el-input v-model="profileData.fullName" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileData.email" />
            </el-form-item>
            
            <el-form-item label="所属学院">
              <el-input v-model="profileData.departmentName" :disabled="true" />
            </el-form-item>
            
            <el-form-item label="所属系">
              <el-input v-model="profileData.majorName" :disabled="true" />
            </el-form-item>

            <el-form-item v-if="isEditing">
              <el-button type="primary" @click="saveProfile">保存</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="role-card">
          <template #header>
            <div class="card-header">
              <span>角色信息</span>
            </div>
          </template>
          
          <div class="role-info">
            <div class="role-item">
              <span class="label">用户类型：</span>
              <el-tag>{{ profileData.userType === 'TEACHER' ? '教师' : '超级管理员' }}</el-tag>
            </div>
            
            <div class="role-item" v-if="adminInfo.level">
              <span class="label">管理员角色：</span>
              <el-tag type="success">{{ adminInfo.label }}</el-tag>
            </div>
            
            <div class="role-item" v-if="adminInfo.level && adminInfo.orgName">
              <span class="label">管理范围：</span>
              <span>{{ adminInfo.orgName }}</span>
            </div>
          </div>
        </el-card>
        
        <el-card class="security-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>安全设置</span>
            </div>
          </template>
          
          <div class="security-actions">
            <div class="security-item">
              <span class="label">密码：</span>
              <span class="value">********</span>
              <el-button link type="primary" @click="showChangePasswordDialog">修改</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="passwordDialogVisible" width="500px">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="120px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TeacherProfilePage'
}
</script>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../../stores/user'
import request from '../../utils/request'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const formRef = ref(null)
const passwordFormRef = ref(null)

// 管理员信息
const adminInfo = computed(() => {
  let level = '';
  let label = '';
  let orgId = null;
  let orgName = '';
  
  if (userStore.userInfo?.userType?.toLowerCase() === 'super_admin') {
    level = 'SUPER_ADMIN';
    label = '超级管理员';
    return { level, label, orgId, orgName };
  }
  
  if (!userStore.userInfo?.extraInfo) {
    return { level, label, orgId, orgName };
  }
  
  try {
    const extraInfo = JSON.parse(userStore.userInfo.extraInfo);
    level = extraInfo.admin_role || '';
    orgId = extraInfo.admin_org_id;
    orgName = extraInfo.admin_org_name || '';
    
    switch (level) {
      case 'SCHOOL_ADMIN':
        label = '校级管理员';
        if (!orgName) orgName = '全校';
        break;
      case 'DEPARTMENT_ADMIN':
        label = '院级管理员';
        break;
      case 'MAJOR_ADMIN':
        label = '系级管理员';
        break;
      case 'CLASS_ADMIN':
        label = '班级管理员';
        break;
    }
  } catch (e) {
    console.error('解析管理员角色失败:', e);
  }
  
  return { level, label, orgId, orgName };
});

// 数据
const isEditing = ref(false);
const passwordDialogVisible = ref(false);
const profileData = ref({});

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单校验规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const rules = {
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
};

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 方法
const loadProfile = async () => {
  try {
    // 从后端获取最新的个人信息
    const response = await request.get(`/users/${userStore.userInfo.userId}/profile`);
    profileData.value = response.data;
  } catch (error) {
    console.error('获取个人信息失败:', error);
    profileData.value = { ...userStore.userInfo };
  }
};

const startEdit = () => {
  isEditing.value = true;
};

const cancelEdit = () => {
  isEditing.value = false;
  loadProfile();
};

const saveProfile = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    // 创建提交对象，仅包含允许编辑的字段
    const updateData = {
      userId: profileData.value.userId,
      fullName: profileData.value.fullName,
      email: profileData.value.email
    };
    
    const response = await request.put(`/users/${profileData.value.userId}`, updateData);
    if (response && response.data) {
      // 更新本地存储的用户信息
      userStore.setUserInfo({
        ...userStore.userInfo,
        fullName: profileData.value.fullName,
        email: profileData.value.email
      });
      
      isEditing.value = false;
      ElMessage.success('个人信息更新成功');
    }
  } catch (error) {
    console.error('保存个人信息失败:', error);
    ElMessage.error('个人信息更新失败');
  }
};

const showChangePasswordDialog = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  };
  passwordDialogVisible.value = true;
};

const changePassword = async () => {
  if (!passwordFormRef.value) return;
  
  try {
    await passwordFormRef.value.validate();
    
    await request.post('/users/change-password', {
      userId: profileData.value.userId,
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    });
    
    passwordDialogVisible.value = false;
    ElMessage.success('密码修改成功');
  } catch (error) {
    console.error('修改密码失败:', error);
    ElMessage.error(error.response?.data?.message || '密码修改失败');
  }
};

// 生命周期
onMounted(() => {
  loadProfile();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  margin-right: 15px;
}

.profile-card, .role-card, .security-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-info, .security-actions {
  padding: 10px 0;
}

.role-item, .security-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.security-item .value {
  flex: 1;
  color: #606266;
}
</style> 